package com.diamond.smart.third.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.StringUtils;
import com.diamond.common.exception.SmartFeignErrorException;
import com.diamond.common.utils.HttpUtils;
import com.diamond.common.utils.R;
import com.diamond.smart.third.feign.ThirdInfoFeignService;
import com.diamond.smart.third.service.MapService;
import com.diamond.smart.third.to.Geocodes;
import com.diamond.smart.third.to.MapResultTo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MapServiceImpl implements MapService {

    public static final String key = "43b4ec0a556c58171261feb31f3adbe7";

    @Autowired
    ThirdInfoFeignService infoFeignService;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public List<Geocodes> getLocation() {

        /*
            String host, String path, String method,Map<String, String> headers,Map<String, String> querys
        */
        String host = "https://restapi.amap.com";
//        String method = "get";
//        Map<String, String> headers = new HashMap<>();
//        Map<String, String> querys = new HashMap<>();
        String path = "/v3/geocode/geo";
        R r = infoFeignService.getDeviceLocation();
        if (r.getCode() == 0) {
            List<String> locations = r.getData(new TypeReference<List<String>>() {});
            String join = StringUtils.join(locations, "|");
            path = path + "?" + "address=" + join + "&batch=true&key=" + key;
        } else {
            throw new SmartFeignErrorException();
        }
        try {
//            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            System.out.println(EntityUtils.toString(response.getEntity()));
            ResponseEntity<String> entity = restTemplate.getForEntity(host + path, String.class);
            if (entity.getStatusCode().is2xxSuccessful()) {
                if (entity.getBody() != null) {
                    String body = entity.getBody();
                    MapResultTo mapResultTo = JSON.parseObject(body, MapResultTo.class);
                    return mapResultTo.getGeocodes();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
